import * as zrender from 'zrender';
import {
  personColumnWidth,
  personColumnPadding,
  barHeight,
  barMargin,
  personColumnZIndex,
} from '../../config';

import { getUniquePersons } from '../../utils';
import { drawHorizontalLines } from '../time-scale/horizontal-lines';
import { createDragHandle, showDragHandle, hideDragHandle, DRAG_HANDLE_WIDTH } from '../row-drag';
import { drawPersonColumnTitle } from './title';

/**
 * 绘制人员信息列
 * @param {object} zr ZRender实例
 * @param {PersonSchedule[]} schedules 人员排班数据
 * @param {ChartState} chartState 图表状态对象
 * @param {RowReorderCallback} onRowReorder 行重排序回调函数
 */
export function drawPersonColumn(
  zr: any,
  schedules: PersonSchedule[],
  chartState: ChartState,
  onRowReorder: RowReorderCallback,
) {
  // 获取去重后的人员列表
  const uniquePersons = getUniquePersons(schedules);

  drawPersonColumnTitle(zr);

  // 计算视口中可见的人员行范围（性能优化）- 现在基于去重后的人员数量
  const firstVisibleRow = Math.max(0, Math.floor(chartState.lastScrollY / (barHeight + barMargin)));
  const lastVisibleRow = Math.min(uniquePersons.length - 1, firstVisibleRow + Math.ceil(chartState.canvasHeight / (barHeight + barMargin)) + 1);

  // 绘制每个人员的信息行
  for (let visibleIndex = firstVisibleRow; visibleIndex <= lastVisibleRow; visibleIndex++) {
    const schedule = uniquePersons[visibleIndex];
    if (!schedule) {
      continue;
    }

    const y = chartState.chartStartY + (barHeight + barMargin) * visibleIndex - chartState.lastScrollY;

    // 如果超出可视区域，跳过
    if (y + barHeight < 0 || y > chartState.canvasHeight) {
      continue;
    }

    // 创建行组以便统一管理悬停事件
    const rowGroup = new zrender.Group();

    // 人员行背景（交替颜色）
    const rowBackground = new zrender.Rect({
      shape: {
        x: DRAG_HANDLE_WIDTH,
        y,
        width: personColumnWidth - DRAG_HANDLE_WIDTH,
        height: barHeight,
      },
      style: {
        fill: visibleIndex % 2 === 0 ? '#ffffff' : '#fafafa',
      },
      z: personColumnZIndex,
      silent: false,
    });

    // 人员姓名（主要信息，左移为拖拽手柄留出空间）
    const nameText = new zrender.Text({
      style: {
        text: `${schedule.person.name} | ${schedule.person.employeeId} | ${schedule.person.department}`,
        x: DRAG_HANDLE_WIDTH + personColumnPadding,
        y: y + barHeight / 2,
        align: 'left',
        verticalAlign: 'middle',
        fontSize: 14,
        fontWeight: 'bold',
        fill: '#333',
      },
      z: personColumnZIndex + 1,
      silent: false,
    });

    // 设置 rowGroup 为非静默模式
    (rowGroup as any).attr('silent', false);
    // 添加元素到行组
    rowGroup.add(rowBackground);
    rowGroup.add(nameText);

    // 创建拖拽手柄（使用绝对索引）
    const dragHandle = createDragHandle(zr, visibleIndex, y, onRowReorder, chartState, uniquePersons.length);

    // 添加悬停事件处理
    const handleMouseEnter = () => {
      showDragHandle(dragHandle);
      // 高亮行背景
      rowBackground.attr('style', {
        fill: 'rgba(0, 123, 255, 0.2)',
      });
    };
    const handleMouseLeave = () => {
      hideDragHandle(dragHandle);
      // 恢复行背景
      rowBackground.attr('style', {
        fill: visibleIndex % 2 === 0 ? '#ffffff' : '#fafafa',
      });
    };

    // 为整个行组添加悬停事件（更可靠的方式）
    rowGroup.on('mouseover', handleMouseEnter);
    rowGroup.on('mouseout', handleMouseLeave);

    // 添加到画布
    zr.add(rowGroup);
    // zr.add(eventCatcher);
    zr.add(dragHandle);
  }

  // 使用统一的水平线绘制组件绘制人员列内的分隔线
  drawHorizontalLines(zr, chartState, schedules, {
    startX: 0,
    endX: personColumnWidth,
    strokeColor: '#e0e0e0',
    lineWidth: 1,
    zIndex: personColumnZIndex,
  });
}
